import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as customerApi from '@/api/customer'
import type { Customer } from '@/types/index'

// 定义客户相关的store
export const useCustomerStore = defineStore('customer', () => {
  // 状态
  const customers = ref<Customer[]>([])
  const currentCustomer = ref<Customer | null>(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取客户列表
  const fetchCustomerList = async (params?: {
    page?: number
    pageSize?: number
    keyword?: string
  }) => {
    loading.value = true
    try {
      const res = await customerApi.getCustomerList(params)
      customers.value = res.data
      total.value = res.total
    } catch (error) {
      console.error('获取客户列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取客户详情
  const fetchCustomerDetail = async (id: string) => {
    loading.value = true
    try {
      const res = await customerApi.getCustomerDetail(id)
      currentCustomer.value = res
    } catch (error) {
      console.error('获取客户详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 搜索客户（用于选择器）
  const searchCustomers = async (params?: {
    customerName?: string
    idType?: string
    idNumber?: string
    page?: number
    pageSize?: number
    keyword?: string
  }) => {
    loading.value = true
    try {
      // 如果提供了customerName、idType、idNumber等详细搜索参数，使用完整的客户列表查询
      if (params?.customerName || params?.idType || params?.idNumber) {
        const res = await customerApi.getCustomerList({
          page: params?.page,
          pageSize: params?.pageSize,
          keyword: params?.customerName || ''
        })
        customers.value = res.data
        total.value = res.total
      } else if (params?.keyword) {
        // 如果只提供了keyword，使用简单搜索
        const res = await customerApi.searchCustomers(params.keyword)
        customers.value = res
        total.value = res.length
      } else {
        // 如果没有提供任何参数，获取全部客户
        const res = await customerApi.getCustomerList({
          page: params?.page,
          pageSize: params?.pageSize
        })
        customers.value = res.data
        total.value = res.total
      }
    } catch (error) {
      console.error('搜索客户失败:', error)
      customers.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取客户名称
  const getCustomerNameById = (id: string): string => {
    const customer = customers.value.find((c: Customer) => c.id === id)
    return customer?.customerName || customer?.name || '未知客户'
  }

  return {
    // 状态
    customers,
    currentCustomer,
    loading,
    total,
    
    // 方法
    fetchCustomerList,
    fetchCustomerDetail,
    searchCustomers,
    getCustomerNameById
  }
})